package com.youwe1.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youwe1.wiki.domain.Content;
import com.youwe1.wiki.domain.Doc;
import com.youwe1.wiki.domain.DocExample;
import com.youwe1.wiki.exception.BusinessException;
import com.youwe1.wiki.exception.BusinessExceptionCode;
import com.youwe1.wiki.mapper.ContentMapper;
import com.youwe1.wiki.mapper.DocMapper;
import com.youwe1.wiki.mapper.DocMapperCust;
import com.youwe1.wiki.req.DocQueryReq;
import com.youwe1.wiki.req.DocSaveReq;
import com.youwe1.wiki.resp.DocQueryResp;
import com.youwe1.wiki.resp.PageResp;
import com.youwe1.wiki.util.CopyUtil;
import com.youwe1.wiki.util.RedisUtil;
import com.youwe1.wiki.util.RequestContext;
import com.youwe1.wiki.util.SnowFlake;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {

    @Resource
    private DocMapper docMapper;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private DocMapperCust docMapperCust;

    @Resource
    private SnowFlake snowFlake;

    @Resource
    public RedisUtil redisUtil;

    @Resource
    public WsService wsService;

    public List<DocQueryResp> findById(Long id) {
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(id);
        // 排序
        docExample.setOrderByClause("sort asc");
        // 查询方法
        List<Doc> docList = docMapper.selectByExample(docExample);
        // 将查询出来的数据处理，去掉无用数据，只返回DocResp里定义的属性
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        return list;
    }

    public List<DocQueryResp> all() {
        DocExample docExample = new DocExample();
        // 排序
        docExample.setOrderByClause("sort asc");
        // 查询方法
        List<Doc> docList = docMapper.selectByExample(docExample);
        // 将查询出来的数据处理，去掉无用数据，只返回DocResp里定义的属性
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        return list;
    }

    public PageResp<DocQueryResp> list(DocQueryReq req) {
        DocExample docExample = new DocExample();
        // 排序
        docExample.setOrderByClause("sort asc");
        // where 条件
        // DocExample.Criteria criteria = docExample.createCriteria();

        List<Doc> docList;
        // 第一页从1开始。而且只会对最近的一条查询方法有效!!!!!
        PageHelper.startPage(req.getPage(), req.getSize());
        // 查询方法
        docList = docMapper.selectByExample(docExample);
        if (req.getPage() > 1 && docList.isEmpty()) {
            // 如果当前页没有数据，页码就减一再次查询
            PageHelper.startPage(req.getPage() - 1, req.getSize());
            docList = docMapper.selectByExample(docExample);
        }
        // 将查询出来的数据处理，去掉无用数据，只返回DocResp里定义的属性
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        // 生成pageInfo用于获取total
        PageInfo<Doc> pageInfo = new PageInfo<>(docList);

        // 分页实例
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setPages(pageInfo.getPages());
        pageResp.setPage(req.getPage());
        pageResp.setSize(req.getSize());
        pageResp.setList(list);
        return pageResp;
    }

    @Transactional
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        Content content = CopyUtil.copy(req, Content.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            doc.setId(snowFlake.nextId());
            // 浏览和阅读初始设置为0
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        } else {
            // 更新
            docMapper.updateByPrimaryKey(doc);

            // 更新为空就插入
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0) {
                contentMapper.insert(content);
            }
        }
    }

    public void delete(List<Long> ids) {
        DocExample docExample = new DocExample();
        // 条件
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);
    }

    public String findContent(Long id) {
        Content content = contentMapper.selectByPrimaryKey(id);
        // 文档阅读数加一
        docMapperCust.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        }
        return content.getContent();
    }

    /**
     * 点赞
     */
    public void vote(Long id) {
        // docMapperCust.increaseVoteCount(id);

        //远程IP+doc.id作为key, 24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 3600 * 24)) {
            docMapperCust.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");
        // 推送消息
        wsService.sendInfo("【" + docDb.getName() + "】被点赞！", logId);
    }

    // 异步化 这里写没用，必须写到另一个类里！！！！！！！！！！
    /*@Async
    public void sendInfo(Long id) {
        Doc docDb = docMapper.selectByPrimaryKey(id);
        webSocketServer.sendInfo("【" + docDb.getName() + "】被点赞！");
    }*/

    public void updateEbookInfo() {
        docMapperCust.updateEbookInfo();
    }
}
